package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/addressBook")
@RestController
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    /**
     * 查看地址
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> listR(){
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getCreateUser,currentId);
        List<AddressBook> list = addressBookService.list(wrapper);
        return R.success(list);
    }

    @PutMapping("/default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook){
        LambdaUpdateWrapper<AddressBook> wrapper=new LambdaUpdateWrapper<>();
        wrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        wrapper.set(AddressBook::getIsDefault,0);
        addressBookService.update(wrapper);
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }

    @PostMapping
    public R<String> post(@RequestBody AddressBook addressBook){
        log.info(addressBook.toString());
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookService.save(addressBook);
        return R.success("添加成功");
    }

    @GetMapping("/{id}")
    public R<AddressBook> get(@PathVariable Long id){
        log.info(id.toString());
        LambdaQueryWrapper<AddressBook> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getId,id);
        AddressBook one = addressBookService.getOne(wrapper);
        return R.success(one);
    }

    @PutMapping
    public R<AddressBook> put1(@RequestBody AddressBook addressBook){
        LambdaQueryWrapper<AddressBook> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getId,addressBook.getId());
        addressBookService.remove(wrapper);
        addressBookService.save(addressBook);
        return R.success(addressBook);
    }

    @GetMapping("/default")
    public R<AddressBook> get1(){
        LambdaQueryWrapper<AddressBook> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getIsDefault,1);
        wrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        AddressBook one = addressBookService.getOne(wrapper);
        return R.success(one);
    }
}
